package com.qyer.commons.concurrent;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * User: Z J Wu Date: 2016/05/11 Time: 11:32 Package: com.qyer.commons.concurrent
 */
public class GenericLinkedBlockingQueue<E> {

  private final String id = RandomStringUtils.randomAlphanumeric(8);

  private final String name;

  private LinkedBlockingQueue<E> queue;

  public static final int MANY = 100000;

  public GenericLinkedBlockingQueue() {
    this.name = UUID.randomUUID().toString();
  }

  public GenericLinkedBlockingQueue(String name) {
    this.name = name;
    this.queue = new LinkedBlockingQueue<>();
  }

  public GenericLinkedBlockingQueue(String name, int capacity) {
    this.name = name;
    this.queue = new LinkedBlockingQueue<>(capacity);
  }

  public E take() throws InterruptedException {
    return this.queue.take();
  }

  public void put(E e) throws InterruptedException {
    if (e == null) {
      return;
    }
    this.queue.put(e);
  }

  public boolean offer(E e) {
    if (e == null) {
      return true;
    }
    this.queue.size();
    return this.queue.offer(e);
  }

  public String getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public int size() {
    return this.queue.size();
  }

  public int remainCapacity() {
    int remain = this.queue.remainingCapacity();
    return remain > MANY ? -1 : remain;
  }

  @Override
  public String toString() {
    return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("id", id)
                                                                      .append("name", name)
                                                                      .toString();
  }
}
